// 是否延迟加载
var lazyOptional = false;

// Datagrid URL参数
var datagrid_url_adv = appPath+'/cms/staticManage_listOptionalAdv.do';
var datagrid_url_adv_mgr = appPath+'/cms/staticManage_listCascadeAdv.do';

/**
 * 待选广告控件初始化方法
 */
function initAdvPlugin() {
	$("#sm_optionalGrid").datagrid({
		url: lazyOptional? '' : datagrid_url_adv,			
		striped: true,
		remoteSort:false,
		queryParams: getAdvQueryParam(),
		idField:'adId',
		checkbox:true,
		frozenColumns:[[
		      {field:'ck',checkbox:true}		      
		]],
		columns:[[
		      {field:'title',title:'标题',width:210,align:'left'},
		      {field:'linkUrl',title:'链接地址',width:180,align:'left'},
		      {field:'remark',title:'描述',width:180,align:'left'},
		      {field:'createDate',title:'创建时间',width:150,align:'left',sortable:true}
		 ]],
		 pagination:true,
		 pageNumber:1,
		 rownumbers:true,
		 toolbar:[{
				id:'btnOptionaladd',
				text:'增加',
				iconCls:'icon-add',
				handler:function(){
					var selections = $("#sm_optionalGrid").datagrid('getSelections');
					if(selections == null || selections == ''){
						$.messager.alert('提示信息','请选择要关联的数据！','info');
						return ;
					}else{
						$("#sm_optionalGrid").datagrid("loading");
						var postData = "[";
						var typeId = $("#optionalDlg").data("typeId");
						for(var i=0; i<selections.length; i++){
							postData += "{\"typeId\":" + typeId + ", \"adId\":" + selections[i].adId + "}";
							postData += (i != selections.length -1? "," : "");
						}
						postData += "]";
						
						$.loading(true);
						$.ajax({
						   type: "POST",
						   url: appPath+'/cms/staticManage_saveCascadeAdv.do',
						   data: "&layoutAdv.jsonData= " + postData,
						   success: function(msg){
							   $.loading(false);
							   if (msg == "ok") 
								   doReloadOptional();
								else {
									$("#sm_optionalGrid").datagrid("loaded");
									$.messager.alert('提示信息','广告关联失败，请稍后重试！','error');									
								}
						   },
						   error: function(XMLHttpRequest, textStatus, errorThrown) {
							   $.loading(false);
							   $("#sm_optionalGrid").datagrid("loaded");
							   $.messager.alert('提示信息','广告关联失败，请稍后重试！','error');
						   }
						});
					}
				}
			},'-',{
				id:'btnOptionalMgr',
				text:'管理',
				iconCls:'icon-reset',
				handler:function(){
					initAdvManagePlugin();
					initSearchItemForManageAdv();
					showDataWindow("#cascadeDlg", $("#optionalDlg").data("typeName") + "陈列管理列表");
				}
			}]
	});
	if (lazyOptional)
		$('#sm_optionalGrid').datagrid('options').url = datagrid_url_adv;
}

/**
 * 广告管理控件初始化方法
 */
function initAdvManagePlugin() {
	$("#sm_cascadeGrid").datagrid({
		url: lazyOptional? '' : datagrid_url_adv_mgr,			
		striped: true,
		remoteSort:false,
		queryParams: getAdvMgrQueryParam(),
		idField:'adId',
		checkbox:true,
		frozenColumns:[[
		      {field:'ck',checkbox:true},
		      {field:'adId',title:'操作',width:40,align:'center',
		    	  formatter:function(value,rowData,rowIndex){
		    	  	  //var dataStr = JSON.stringify(rowData);
		    		  return "<a href='javascript:void(0)'><img border='0' width='12px' height='12px'  src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='编辑' onClick='showLayoutAdvEdit("+rowIndex+")'/></a>";
		    	  }
		      }
		]],
		columns:[[
		      {field:'title',title:'标题',width:210,align:'left'},
		      {field:'linkUrl',title:'链接地址',width:145,align:'left'},
		      {field:'publishStartTime',title:'发布起始时间',width:113,align:'left',sortable:true,
		    	  formatter:function(value,rowData){
		    		  return $.DateUtil.format(new Date(rowData.layoutAdv.publishStartTime),'yyyy-MM-dd hh:mm:ss');
		    	  }
		      },
		      {field:'publishEndTime',title:'发布截止时间',width:113,align:'left',sortable:true,
		    	  formatter:function(value,rowData){
		    		  return $.DateUtil.format(new Date(rowData.layoutAdv.publishEndTime),'yyyy-MM-dd hh:mm:ss');
		    	  }
		      },
		      {field:'sortNo',title:'排序',width:49,align:'center',sortable:true,
		    	  formatter:function(value,rowData){
		    		  return rowData.layoutAdv.sortNo;
		    	  }
		      }
		 ]],
		 pagination:true,
		 pageNumber:1,
		 rownumbers:true,
		 toolbar:[{
				id:'btndelMuLayoutAdv',
				text:'删除',
				iconCls:'icon-cancel',
				handler:function(){
					var selections = $("#sm_cascadeGrid").datagrid('getSelections');
					if(selections == null || selections == ''){
						$.messager.alert('提示信息','请选择要删除的数据','info');
						return ;
					}else{
						$.messager.confirm('提示信息','您确定要删除这些记录？',function(r){
							if(r){
								var ids = '';
								for(var i=0;i<selections.length;i++){
									ids += selections[i].adId+',';
								}
								ids = ids.substring(0,ids.lastIndexOf(','));
								
								$.loading(true);
								$.ajax({
									url:appPath+'/cms/staticManage_delMultiCascadeAdv.do',
									data:"&multi_id=" + ids + "&layoutAdv.typeId=" + $("#optionalDlg").data("typeId"),
									success:function(data){
										$.loading(false);
										if(data!='ok'){
											$.messager.alert('提示信息','抱歉，删除未能完成，'+data,'error');
										}else{
											doReloadCascade("delete");
										}
									},
									error:function(XMLHttpRequest, textStatus, errorThrown){
										$.loading(false);
										$.messager.alert('提示信息','抱歉，删除未能完成，'+textStatus,'error');
									}
								});		
							}
						});
					}
				}
			}]
	});
	if (lazyOptional)
		$('#sm_cascadeGrid').datagrid('options').url = datagrid_url_adv_mgr;
}

/**
 * 展现广告陈列编辑页面
 * @param {} rowData
 */
function showLayoutAdvEdit(rowIndex){
	var rowData = $("#sm_cascadeGrid").datagrid("getRows")[rowIndex];
	$('#editLayoutAdvForm').form('clear');
	$('#editLayoutAdvForm').form('load',rowData);
	
	$("#layoutAdv_startTime").datetimebox("setValue", rowData.layoutAdv.publishStartTime);
	$("#layoutAdv_adId").val(rowData.adId);
	$("#layoutAdv_typeId").val(rowData.layoutAdv.typeId);
	
	$("#layoutAdv_title").html(rowData.title);
	$("#layoutAdv_url").html("<a href='"+rowData.linkUrl+"' target='_blank'>"+rowData.linkUrl+"</a>");
	$("#layoutAdv_createTime").html($.DateUtil.format(new Date(rowData.createTime),'yyyy-MM-dd hh:mm:ss'));
	$("#layoutAdv_updateTime").html($.DateUtil.format(new Date(rowData.updateTime),'yyyy-MM-dd hh:mm:ss'));
	$("#layoutAdv_remark").html(rowData.remark);
	
	$('#editLayoutDlg').window({
			title:'广告陈列编辑页面',
			iconCls:'icon-edit',
			height: 490,
			modal: true,
			shadow: true,
			collapsible:false,
			minimizable:false,
			maximizable:false
		});
	showRelatedSearchItem('#editLayoutAdvForm');
	$('#editLayoutDlg').window('move',{top:100});
	$('#editLayoutDlg').window('open');
	$('#layoutAdv_sortNo').focus();
	$("#ensureBtn").unbind();
	$("#ensureBtn").bind("click", doPostLayoutAdvData);
	
	$('#layoutAdv_sortNo').val(rowData.layoutAdv.sortNo); 
	$("#layoutAdv_endTime").datetimebox("setValue", $.DateUtil.format(new Date(rowData.layoutAdv.publishEndTime),'yyyy-MM-dd hh:mm:ss'));
}

/**
 * 提交数据
 */
function doPostLayoutAdvData(){
	if(!$('#editLayoutAdvForm').form('validate')){
		return ;
	}	
	var subData = $('#editLayoutAdvForm');  
    var layoutAdv = subData.serialize();    
	
    $.loading(true);
	$.ajax({
		url:appPath+'/cms/staticManage_updateCascadeAdv.do',
		type:"post",
		data:layoutAdv,
		success:function(data){
			$.loading(false);
			if(data!='ok'){
				$.messager.alert('提示信息','抱歉，更新未能完成！','error');
			}else{
				closeLayoutWindow();
				doReloadCascade("update");
			}
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			$.loading(false);
			$.messager.alert('提示信息','抱歉，更新未能完成，'+textStatus,'error');
		}
	});
}

/**
 * 获取参数列表
 * @return {}
 */
function getAdvQueryParam(){
	var queryObject = new Object();
	queryObject["adv.layoutAdv.typeId"] = $("#optionalDlg").data("typeId");
	queryObject["adv.title"] = $.trim($("#adv_title").val());
	return queryObject;
}

/**
 * 查询可选数据
 */
function doQueryAdv(){
	$("#sm_optionalGrid").datagrid('unselectAll');
	$("#sm_optionalGrid").datagrid('load',getAdvQueryParam());
}

/**
 * 获取广告管理参数列表
 * @return {}
 */
function getAdvMgrQueryParam(){
	var queryObject = new Object();
	queryObject["adv.layoutAdv.typeId"] = $("#optionalDlg").data("typeId");
	queryObject["adv.title"] = $.trim($("#advMgr_title").val());
	return queryObject;
}

/**
 * 查询广告管理数据
 */
function doQueryAdvMgr(){
	$("#sm_cascadeGrid").datagrid('unselectAll');
	$("#sm_cascadeGrid").datagrid('load',getAdvMgrQueryParam());
}

/**
 * 初始化待选广告搜索项
 */
function initSearchItemForOptionalAdv() {	
	showRelatedSearchItem("#advTable");
}

/**
 * 初始化广告管理搜索项
 */
function initSearchItemForManageAdv() {
	showRelatedSearchItem("#advMgrTable");
}



